<template>
  <div v-if="isShow">
    <el-form :model="formData" ref="formRef" label-width="140px">
      <el-form-item label="甲方专业组长">
        <!-- <el-select-v2
          v-model="formData.roleCode1"
          filterable
          :options="userList"
          placeholder="请选择人员"
          style="width: 215px"
        >
        </el-select-v2> -->

        <el-select
          key="roleCode1"
          v-model="formData.roleCode1"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData1"
          value-key="userId"
        >
          <!-- reserve-keyword -->
          <el-option
            v-for="item in userList1"
            :key="item.userId"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>

        <p
          v-if="copyFormData.copyRoleCode1 !== formData.roleCode1"
          class="title"
        >
          <i class="el-icon-info"></i>
          <span class="title-tip"> 更改后将影响业务流程处理人权限 </span>
        </p>
      </el-form-item>
      <el-form-item label="甲方副组长">
        <el-select
          key="roleCode2"
          v-model="formData.roleCode2"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData2"
          value-key="userId"
        >
          <!-- reserve-keyword -->
          <el-option
            v-for="item in userList2"
            :key="item.userId"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <p
          v-if="copyFormData.copyRoleCode2 !== formData.roleCode2"
          class="title"
        >
          <i class="el-icon-info"></i>
          <span class="title-tip"> 更改后将影响业务流程处理人权限 </span>
        </p>
      </el-form-item>
      <el-form-item label="甲方执行组长">
        <el-select
          key="roleCode3"
          v-model="formData.roleCode3"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData3"
          value-key="userId"
        >
          <!-- reserve-keyword -->
          <el-option
            v-for="item in userList3"
            :key="item.userId"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <p
          v-if="copyFormData.copyRoleCode3 !== formData.roleCode3"
          class="title"
        >
          <i class="el-icon-info"></i>
          <span class="title-tip"> 更改后将影响业务流程处理人权限 </span>
        </p>
      </el-form-item>
      <el-form-item label="乙方单位负责人">
        <el-select
          key="roleCode4"
          v-model="formData.roleCode4"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData4"
          value-key="userId"
        >
          <!-- reserve-keyword -->
          <el-option
            v-for="item in userList4"
            :key="item.userId"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <p
          v-if="copyFormData.copyRoleCode4 !== formData.roleCode4"
          class="title"
        >
          <i class="el-icon-info"></i>
          <span class="title-tip">
            更改后将变更合同负责人信息，且会影响业务流程处理人权限
          </span>
        </p>
      </el-form-item>
      <el-form-item label="监理单位负责人">
        <el-select
          key="roleCode5"
          v-model="formData.roleCode5"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData5"
          value-key="userId"
        >
          <!-- reserve-keyword -->
          <el-option
            v-for="item in userList5"
            :key="item.userId"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <p
          v-if="copyFormData.copyRoleCode5 !== formData.roleCode5"
          class="title"
        >
          <i class="el-icon-info"></i>
          <span class="title-tip"> 更改后将影响业务流程处理人权限 </span>
        </p>
      </el-form-item>
      <el-form-item label="甲方单位负责人">
        <el-select
          key="roleCode6"
          v-model="formData.roleCode6"
          filterable
          remote
          placeholder="请输入姓名"
          :remote-method="getTableData6"
          value-key="userId"
        >
          <!-- reserve-keyword -->
          <el-option
            v-for="item in userList6"
            :key="item.userId"
            :label="item.label"
            :value="item"
          >
          </el-option>
        </el-select>
        <p
          v-if="copyFormData.copyRoleCode6 !== formData.roleCode6"
          class="title"
        >
          <i class="el-icon-info"></i>
          <span class="title-tip">
            更改后将变更合同负责人信息，且会影响业务流程处理人权限
          </span>
        </p>
      </el-form-item>
    </el-form>
    <el-row justify="end">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, ref, defineProps, onMounted } from "vue";
import { getUserList, postUserInfo } from "/@/api/user";

import { postProTeamMembePrsSave, getProTeamMembers } from "/@/api/project";
// import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import { cloneDeep } from "lodash-es";
// import { useActiveElement } from "@vueuse/core";

// const router = useRouter();
// const route = useRoute();
const formRef = ref<HTMLFormElement | null>(null) as any;
const emit = defineEmits(["update:dialogVisibleGroup", "resetGetData"]);
const props = defineProps({
  nodeId: {
    type: Number,
    default: 0
  },
  contractInfo: {
    type: Object,
    default: () => {}
  },
  mode: {
    type: String,
    default: "add"
  }
});
let isShow = ref(false);

let formData = reactive({
  roleCode1: null,
  roleCode2: null,
  roleCode3: null,
  roleCode4: null,
  roleCode5: null,
  roleCode6: null
});

let copyFormData = reactive({
  copyRoleCode1: "",
  copyRoleCode2: "",
  copyRoleCode3: "",
  copyRoleCode4: "",
  copyRoleCode5: "",
  copyRoleCode6: ""
});

let userList1 = ref([]);
let userList2 = ref([]);
let userList3 = ref([]);
let userList4 = ref([]);
let userList5 = ref([]);
let userList6 = ref([]);

// const currentInfo = toRef(props, "contractInfo");

async function getTableData1(query = "") {
  if (!query) {
    userList1.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList1.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableData2(query = "") {
  if (!query) {
    userList2.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList2.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableData3(query = "") {
  if (!query) {
    userList3.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList3.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableData4(query = "") {
  if (!query) {
    userList4.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList4.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableData5(query = "") {
  if (!query) {
    userList5.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList5.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

async function getTableData6(query = "") {
  if (!query) {
    userList6.value = [];
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: query
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      userList6.value = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });
    }
  } catch (err) {
    console.log(err);
  }
}

const handleSubmit = async () => {
  try {
    const copyFormData = cloneDeep(formData);
    const memberTypeList = filterUserData(copyFormData);
    console.log(memberTypeList, "memberTypeList");

    let params = {
      projectId: props.contractInfo.projectManageId,
      contractId: props.contractInfo.id,
      memberTypeList
    };
    console.log(params, "params");
    const { code } = await postProTeamMembePrsSave(params);
    if (code === 200) {
      NotifMessage.success("修改成功");
      resetTableData();
    }
  } catch (err) {
    console.log(err);
  }
};

const getInitData = async () => {
  try {
    const params = {
      id: props.contractInfo.id
    };
    const { code, data } = await getProTeamMembers(params);
    if (code === 200) {
      const userList = [
        ...new Set(
          data.memberTypeList.map(item => {
            return item.userId;
          })
        )
      ];
      const resUser = await searchUserName(userList);

      // 去重后给userList 列表赋值
      let obj = {};
      userList1.value = userList1.value
        .concat(resUser)
        .reduce(function (item, next) {
          obj[next.userId] ? "" : (obj[next.userId] = true && item.push(next));
          return item;
        }, []);

      userList2.value = JSON.parse(JSON.stringify(userList1.value));
      userList3.value = JSON.parse(JSON.stringify(userList1.value));
      userList4.value = JSON.parse(JSON.stringify(userList1.value));
      userList5.value = JSON.parse(JSON.stringify(userList1.value));
      userList6.value = JSON.parse(JSON.stringify(userList1.value));

      data.memberTypeList.length &&
        data.memberTypeList.forEach(item => {
          if (item.roleCode) {
            const filterItem = resUser.filter(i => {
              return i.userId === item.userId;
            });
            formData[`roleCode${item.roleCode}`] = filterItem[0];
          }
        });

      copyFormData.copyRoleCode1 = formData.roleCode1;
      copyFormData.copyRoleCode2 = formData.roleCode2;
      copyFormData.copyRoleCode3 = formData.roleCode3;
      copyFormData.copyRoleCode4 = formData.roleCode4;
      copyFormData.copyRoleCode5 = formData.roleCode5;
      copyFormData.copyRoleCode6 = formData.roleCode6;

      // console.log(userListCache, formData, copyFormData);

      isShow.value = true;
    }
  } catch (err) {
    console.log(err);
  }
};

const roleMap = new Map([
  ["roleCode1", 1],
  ["roleCode2", 2],
  ["roleCode3", 3],
  ["roleCode4", 4],
  ["roleCode5", 5],
  ["roleCode6", 6]
]);

const filterUserData = data => {
  let composeList = [];
  const dataCopy = JSON.parse(JSON.stringify(data));
  const keyList = Object.keys(dataCopy);
  keyList.forEach(item => {
    if (dataCopy[item]?.userId) {
      dataCopy[item].roleCode = roleMap.get(item);
      composeList.push(dataCopy[item]);
    }
  });

  return composeList;
};

// 关闭弹框并更新数据
const resetTableData = () => {
  emit("update:dialogVisibleGroup", false);
  emit("resetGetData");
};

const handleCancel = () => {
  emit("update:dialogVisibleGroup", false);
};

onMounted(async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100,
      nameLike: ""
    };
    const { code, data } = await getUserList(params);
    if (code === 200) {
      const resList = data.list.map(item => {
        return {
          userId: item.id,
          userName: item.name,
          label: `${item.name}(${item.userName})`
        };
      });

      userList1.value = resList;
      userList2.value = resList;
      userList3.value = resList;
      userList4.value = resList;
      userList5.value = resList;
      userList6.value = resList;
    }
  } catch (err) {
    console.log(err);
  }

  await getInitData();
});

// 根据id 查询用户名
const searchUserName = async userList => {
  if (!userList.length) return;
  let promises = userList.map(user => {
    return postUserInfo({ id: user });
  });
  let results = await Promise.all(promises);
  // console.log(results, "results");
  const users = results.map(item => {
    return {
      userId: (item as any)?.data.id,
      label: `${(item as any)?.data.name}(${(item as any)?.data.userName})`,
      userName: (item as any)?.data.name
    };
  });

  return users;
};
</script>

<style lang="scss" scoped>
.title {
  font-size: 12px;
  line-height: 18px;
  &-tip {
    color: #f56c6c;
  }
}
</style>
